package com.fen.demo020;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.GenericApplicationContext;

/**
 * @author lrf
 */
@Configuration
public class SingerConfig {

    @Lazy
    @Bean(initMethod = "init")
    Singer singerOne(){
        Singer singerOne = new Singer();
        singerOne.setName("deng chao");
        singerOne.setAge(22);
        return singerOne;
    }

    @Lazy
    @Bean(initMethod = "init")
    Singer singerTwo(){
        Singer singerTwo = new Singer();
        singerTwo.setAge(30);
        return singerTwo;
    }

    @Lazy
    @Bean(initMethod = "init")
    Singer singerThree(){
        Singer singerThree = new Singer();
        singerThree.setName("Default Three Name");
        return singerThree;
    }

    public static void main(String[] args) {
        GenericApplicationContext context = new AnnotationConfigApplicationContext(SingerConfig.class);
        getBean("singerOne", context);
        getBean("singerTwo", context);
        getBean("singerThree", context);
        context.close();
    }

    public static Singer getBean(String branName, ApplicationContext context) {
        try {
            Singer bean = (Singer) context.getBean(branName);
            System.out.println("bean = " + bean);
            return bean;
        } catch (BeanCreationException ex) {
            System.out.println("An error occured in bean configuration: " + ex.getMessage());
            return null;
        }
    }

}